#/bin/zsh

# set -e

#获取硬件信息
UNAME_MACHINE="$(uname -m)"

# Default settings
INIT_DIR="${INIT_DIR:-$HOME/.init}"
INITRC="${INIT_DIR}/.initrc"
# REPO=${REPO:-ohmyzsh/ohmyzsh}
# REMOTE=${REMOTE:-https://github.com/${REPO}.git}

# brew 默认安装的软件
BREW_SOFTWARE=('git-open' bat wget)
BREW_SOFTWARE_CASK=('4k-video-downloader' docker 'google-chrome' iina iterm2 maczip 'microsoft-remote-desktop' motrix postman sourcetree vlc utools 'youtube-dl')

# zsh 插件字符串
ZSH_PLUGINS_STRING="git"

# 判断是Linux还是Mac os
OS="$(uname)"
if [[ "$OS" == "Linux" ]]; then
  # HOMEBREW_ON_LINUX=1
  echo "暂时只支持 macos 初始化"
  exit 1
elif [[ "$OS" != "Darwin" ]]; then
  echo "Homebrew 只运行在 Mac OS 或 Linux."
fi

# 字符串染色程序
if [[ -t 1 ]]; then
  tty_escape() { printf "\033[%sm" "$1"; }
else
  tty_escape() { :; }
fi
tty_universal() { tty_escape "0;$1"; } #正常显示
tty_mkbold() { tty_escape "1;$1"; } #设置高亮
tty_underline="$(tty_escape "4;39")" #下划线
tty_blue="$(tty_universal 34)" #蓝色
tty_red="$(tty_universal 31)" #红色
tty_green="$(tty_universal 32)" #绿色
tty_yellow="$(tty_universal 33)" #黄色
tty_bold="$(tty_universal 39)" #加黑
tty_cyan="$(tty_universal 36)" #青色
tty_reset="$(tty_escape 0)" #去除颜色

BREW_INSTALLED=""
BREW_INSTALL_FAILED=""
function brew_install () {
  if [[ 1 -eq "$#" ]] ; then
    echo "${tty_green}Installing $1 using brew${tty_reset}"
    brew install $1 && err=0 || err=1
    if [[ $err -eq 1 ]]; then
        BREW_INSTALL_FAILED="${BREW_INSTALL_FAILED} $1"
    fi
    BREW_INSTALLED="${BREW_INSTALLED} $1"

		return 0
	else
	  for software in "$@" ; do
      brew_install $software
    done
  fi
}

BREW_CASK_INSTALL_FAILED=""
function brew_cask_install () {
  if [[ 1 -eq "$#" ]] ; then
    echo "${tty_green}Installing $1 using brew cask ${tty_reset}"
    brew install --cask $1 && err=0 || err=1
    if [[ $err -eq 1 ]]; then
      BREW_CASK_INSTALL_FAILED="${BREW_CASK_INSTALL_FAILED} $1"
    fi

    BREW_INSTALLED="${BREW_INSTALLED} $1"
		return 0
	else
	  for software in "$@" ; do
      brew_cask_install $software
    done
  fi
}

#用户输入极速安装speed，git克隆只取最近新版本
#但是update会出错，提示需要下载全部数据
GIT_SPEED=""
SPEED=""
if [[ "$0" == "speed" ]]
then
  GIT_SPEED="--depth=1"
  SPEED="speed"
else
  for dir in $@; do
    if [[ $dir == "speed" ]]
    then
      GIT_SPEED="--depth=1"
      SPEED="speed"
    fi
  done
fi

# 是否安装收费软件
INSTALL_CHARGE=""
if [[ "$0" == "charge" ]]
then
  INSTALL_CHARGE="charge"
else
  for str in $@; do
    if [[ $str == "charge" ]]
    then
      # echo $str
      INSTALL_CHARGE="charge"
    fi
  done
fi

mkdir -p $INIT_DIR


# return 1: 已安装， 0: 未安装
installed() {
  if ! type "$1" >/dev/null 2>&1
  then
    return 0
  fi

  return 1
}

# 使用国内开源脚本进行安装
installed 'brew'

if [[ 0 -eq "$?" ]]
then
  echo "${tty_green}install homebrew${tty_reset}"
  /bin/zsh -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/Homebrew.sh)" $SPEED
  source $HOME/.zprofile
fi


# 卸载 brew
# /bin/zsh -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/HomebrewUninstall.sh)"


# software install: ohmyzsh
if [[ ! -d $ZSH ]]
then
  echo "${tty_green}install oh my zsh${tty_reset}"
  echo Y | sh -c "REPO='mirrors/ohmyzsh'; REMOTE='https://gitee.com/mirrors/ohmyzsh.git' ; $(curl -fsSL https://gitee.com/mirrors/oh-my-zsh/raw/master/tools/install.sh)"
  if [[ 0 -eq "$?" ]] ;
  then
    echo "${tty_green} oh my zsh 安装成功${tty_reset}"
  else
    echo "${tty_red} h my zsh 安装失败${tty_reset}"
  fi
fi

# 卸载 omz
#sh -c "REPO='mirrors/ohmyzsh'; REMOTE='https://gitee.com/mirrors/ohmyzsh.git' ;$(curl -fsSL https://gitee.com/mirrors/oh-my-zsh/raw/master/tools/uninstall.sh)"

# 更新 omz
#sh -c "$(curl -fsSL https://gitee.com/mirrors/oh-my-zsh/raw/master/tools/upgrade.sh)"

echo "${tty_green}Installing software using HomeBrew: ${tty_reset}"
# software install: 常用免费软件
for software in $BREW_SOFTWARE ; do
  brew_install $software
done

for software in $BREW_SOFTWARE_CASK ; do
  brew_cask_install $software
done


echo "${tty_green}install zsh plugins${tty_reset}"
brew install autojump zsh-autosuggestions zsh-completions zsh-syntax-highlighting
# 插件使用参考网址：https://hufangyun.com/2017/zsh-plugin/


# # 应该生成配置文件
echo "${tty_green}配置 oh my zsh${tty_reset}"
echo '
if type brew &>/dev/null
then
    FPATH=$(brew --prefix)/share/zsh-completions:$FPATH

    autoload -Uz compinit
    compinit
fi
source $(brew --prefix)/share/zsh-autosuggestions/zsh-autosuggestions.zsh
source $(brew --prefix)/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
# ; export ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR=$(brew --prefix)/share/zsh-syntax-highlighting/highlighters
# zsh plugins end
' > $INITRC
# echo $INITRC
ZSH_PLUGINS_STRING="${ZSH_PLUGINS_STRING} autojump command-not-found docker docker-compose heroku pip sudo"
compaudit | xargs chmod go-w

echo "${tty_green}配置 git${tty_reset}"
[ !  -f ${INIT_DIR}/.gitignore_global ] && touch ${INIT_DIR}/.gitignore_global || echo "file ${INIT_DIR}/.gitignore_global is already exists."
git config --global core.safecrlf true
git config --global core.excludesfile ${INIT_DIR}/.gitignore_global


# software install: PHP
setup_php () {
  echo "${tty_green}install PHP${tty_reset}"
  brew_install php composer brew-php-switcher
  # software composer settings
  composer config -g optimize-autoloader true
  composer config -g preferred-install dist
  composer config -g sort-packages true
  composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/
  # composer config -g --unset repos.packagist
  # composer global require friendsofphp/php-cs-fixer phing/phing phpmd/phpmd phpstan/phpstan squizlabs/php_codesniffer vimeo/psalm

  if [[ ! -z "$INSTALL_CHARGE" ]] ;
  then
    brew_cask_install phpstorm
  fi
}

setup_javascript () {
  echo "${tty_green}install javascript: ${tty_reset}"
  brew_install node
  brew_cask_install visual-studio-code

  echo '# nodejs setting' >> $INITRC
  echo 'export PATH="$(brew --prefix)/opt/node/bin:$PATH"' >> $INITRC
  echo 'export LDFLAGS="-L$(brew --prefix)/opt/node/lib"' >> $INITRC
  echo 'export CPPFLAGS="-I$(brew --prefix)/opt/node/include"' >> $INITRC
  export PATH="$(brew --prefix)/opt/node/bin:$PATH"
  npm install -g nrm
  nrm use taobao
  # TODO: nvm 安装使用
  # mkdir -p ~/.nvm
  # echo 'export NVM_DIR="$HOME/.nvm"
  # [ -s "/opt/homebrew/opt/nvm/nvm.sh" ] && \. "/opt/homebrew/opt/nvm/nvm.sh"  # This loads nvm
  # [ -s "/opt/homebrew/opt/nvm/etc/bash_completion.d/nvm" ] && \. "/opt/homebrew/opt/nvm/etc/bash_completion.d/nvm"  # This loads nvm bash_completion
  # ' > $INITRC

  # software install: 收费软件
  if [[ ! -z "$INSTALL_CHARGE" ]] ;
  then
    brew_cask_install webstorm
  fi
}

setup_db () {
  echo "${tty_green}install database manager tools:${tty_reset}"
  brew_cask_install another-redis-desktop-manager mysqlworkbench
  # software install: 收费软件
  if [[ ! -z "$INSTALL_CHARGE" ]] ;
  then
    brew_cask_install datagrip
  fi
}

setup_tencent () {
  echo "${tty_green}install 腾讯全家桶${tty_reset}"
  brew_cask_install tencent-lemon qq wechat qqmusic
}

setup_bashrc () {
  echo "

${tty_red}替换 ~/.zshrc 中的 plugins=(git)${tty_reset}
  ${tty_green} plugins=(${ZSH_PLUGINS_STRING})${tty_reset}

通过 brew 安装的软件

    ${tty_green}${BREW_INSTALLED} ${tty_reset}


通用忽略配置文件: ${tty_green}${INIT_DIR}/.gitignore_global${tty_reset}

  可能需要运行的配置
  ${tty_green}
     git config --global user.name 'username'
     git config --global user.email 'sample@qq.com'
  ${tty_reset}"

  [ ! -z $BREW_INSTALL_FAILED ] && echo "${tty_red}安装失败的软件，重新安装命令${tty_reset}: ${tty_green}breew install ${BREW_INSTALL_FAILED}${tty_reset}"
  [ ! -z $BREW_CASK_INSTALL_FAILED ] && echo "${tty_red}安装失败的软件，重新安装命令${tty_reset}: ${tty_green}breew install --cask ${BREW_CASK_INSTALL_FAILED}${tty_reset}"

  [[ `grep -c '.init/' ${HOME}/.zshrc` -ne '0' ]] || echo "source ${INITRC}" >> ${HOME}/.zshrc
  # source ${INITRC}

  echo "${tty_red} 重启终端 或者 运行${tty_bold} source ${HOME}/.zshrc  ${tty_reset} ${tty_red}否则可能无法使用${tty_reset}"
}

for str in $@; do
  if [[ "$str" = 'all' || "$str" == "php" ]] ; then
    setup_php
  fi

  if [[ "$str" = 'all' || "$str" == "js" || "$str" == "javascript" ]] ; then
    setup_javascript
  fi

  if [[ "$str" = 'all' || "$str" == "db" ]] ; then
    setup_db
  fi

  if [[ "$str" = 'all' || "$str" == "tencent" ]] ; then
    setup_tencent
  fi
done

setup_bashrc

echo
echo
echo "${tty_green} done.${tty_reset}"
echo
echo

